package com.wnxy.pms.product.core.service.impl;

import com.wnxy.pms.product.core.constant.PromotionStatus;
import com.wnxy.pms.product.core.constant.RedisConstant;
import com.wnxy.pms.product.core.entity.Product;
import com.wnxy.pms.product.core.mapper.ProductMapper;
import com.wnxy.pms.product.core.service.IProductService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wnxy.pms.product.core.vo.PromotionProductVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * <p>
 * 商品表 服务实现类
 * </p>
 *
 * @author Jet
 * @since 2022-06-06
 */
@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements IProductService {

    @Autowired
    private RedisTemplate redisTemplate;

    // 缓存击穿
    //@Cacheable(value = "product:seckill",key = "'list'")
    //public List<PromotionProductVo> findPromotionSeckill() {
    //    return baseMapper.findPromotionSeckill(PromotionStatus.START_STATUS);
    //}

    @Override
    public List<PromotionProductVo> findPromotionSeckill() {
        //1. 先从Redis中获取秒杀活动列表。（定时任务进行的数据预热，所以是可以直接从redis中获取的）
        List<PromotionProductVo> seckillList =
                redisTemplate.opsForList().range(RedisConstant.PRODUCT_SECKILL, 0, -1);

        //2. 判断
        if (CollectionUtils.isEmpty(seckillList)) {
            // 2.1 没有从缓存中获取到数据，查询数据库。 （可能数据预热有问题）
            seckillList =baseMapper.findPromotionSeckill(PromotionStatus.START_STATUS);
            // 2.2 把查询结果放入缓存
            redisTemplate.opsForList().leftPushAll(RedisConstant.PRODUCT_SECKILL,seckillList);
        }
        //3. 已经从缓存中获取到数据，就直接返回
        return seckillList;
    }

    @Override
    public List<PromotionProductVo> findPromotionSeckillByStatus(int status) {
        return baseMapper.findPromotionSeckill(status);
    }
}
